var officegen = require('officegen');
var fs = require('fs');
var path = require('path');
var docx = officegen ( 'docx' );
var async = require('async');
var wrapWorld=require('./WrapWord')

/**
 * 导出word
 */

function ExportWorld(){

}

ExportWorld.prototype.exportWord = function( res ,parameters) {
    console.log('exportWord-------------');
    docx.on ( 'finalize', function ( written ) {
                console.log ( 'Finish to create Word file.\nTotal bytes created: ' + written + '\n' );
            });


    docx.on ( 'error', function ( err ) {
                console.log ( err );
            });




var table = [
    [{
      val: "title",
      opts: {
        cellColWidth: 1261,
        b:true,
        sz: '48',
        align: "left",
        shd: {
          fill: "7F7F7F",
          themeFill: "text1",
          "themeFillTint": "80"
        },
        fontFamily: "Avenir Book"
      }
    },{
      val: "content",
      opts: {
        b:true,
        cellColWidth: 1461,
        align: "left",
        shd: {
          fill: "92CDDC",
          themeFill: "text1",
          "themeFillTint": "80"
        }
      }
    }
    ],
    
  ]
   if(parameters.tableData){
       for(var i=0;i<parameters.tableData.length;i++){
           var itemObj=parameters.tableData[i];
           table.push([itemObj.title,itemObj.content])
       }
   }
   console.log(table)
  var tableStyle = {
    tableColWidth: 1336,
    tableSize: 24,
    tableColor: "ada",
    tableAlign: "left",
    tableFontFamily: "Comic Sans MS",
    borders: true
  }
   
  var pTableObj=docx.createTable (table, tableStyle);






    console.log(parameters)
    var imageTable=[]
    if(parameters.images){
        var images=parameters.images;
        for(var i=0;i<images.length;i++){
            if(i%2 == 0){
                pObj=docx.createP()
            }
            var img=images[i];
            console.log(img)
           wrapWorld.addImage(pObj,img,{width:250,height:250});
    
        }
    }

   




    var out = fs.createWriteStream ( 'out.docx' );// 文件写入
    out.on ( 'error', function ( err ) {
        console.log ( err );
    });


    var result = docx.generate (out);// 服务端生成word

  
    res.writeHead ( 200, {

// 注意这里的type设置，导出不同文件type值不同application/vnd.openxmlformats-officedocument.presentationml.presentation
        "Content-Type": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", 

 'Content-disposition': 'attachment; filename=out.docx'

    });
    docx.generate (res);// 客户端导出word

    return "out.docx"


}


module.exports=(function(){

    return new ExportWorld()
})()